package org.mobile.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mobile.beans.Order;
import org.mobile.beans.Phone;
import org.mobile.beans.User;
import org.mobile.logic.OrderLogic;

/**
 * Servlet implementation class AddOrder
 */
@WebServlet(name = "addOrder", urlPatterns = { "/addOrder" })
public class AddOrder extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddOrder() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Phone> phoneList= (List<Phone>)request.getSession().getAttribute("cart");
		int userID= ((User)request.getSession().getAttribute("user")).getId();
		if(phoneList != null){
			if(!OrderLogic.getInstance().addOrder(userID, phoneList, Order.STATUS_WAITING)){
				request.setAttribute("error", "Błąd dodawania zamówienia!");
				request.getRequestDispatcher("errPage.jsp").forward(request, response);
			}
			else{
				request.setAttribute("message", "Dodano zamówinie!");
				request.getSession().removeAttribute("cart");
				request.getRequestDispatcher("index.jsp").forward(request, response);
			}
		}
	}

}
